package shoozhoo.libandrotranslation;

import java.io.IOException;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.os.AsyncTask;

/*
 * Google Language API Client
 *
 * http://code.google.com/intl/ja/apis/language/
 */
public abstract class GoogleLanguageClient extends AsyncTask<String, Void, JSONObject>{
	private static final String GoogleLanguageURL = "https://ajax.googleapis.com/ajax/services/language/translate";
	private static final String JsonParamData = "responseData";
	private static final String JsonParamTranslated = "translatedText";
	private static final String JsonParamStatus = "responseStatus";
	private static final String JsonParamDetails = "responseDetails";


	private DefaultHttpClient client;
	private String toLang;

	public GoogleLanguageClient(String toLang){
		this.toLang = toLang;
		this.client = new DefaultHttpClient();
		this.client.getParams().setIntParameter("http.socket.timeout", 10*1000);
		this.client.getParams().setIntParameter("http.connection.timeout", 10*1000);
	}

	@Override
	protected JSONObject doInBackground(String... params) {
		try{
			String str = params[0];
			HttpResponse res = transRequest(str, this.toLang);
			if(res.getStatusLine().getStatusCode()!=200){
				JSONObject jo = new JSONObject();
				jo.put(JsonParamData, null);
				jo.put(JsonParamStatus, res.getStatusLine().getStatusCode());
				jo.put(JsonParamDetails, res.getStatusLine().getReasonPhrase());
				return jo;
			}

			String strJson = EntityUtils.toString(res.getEntity());
			//AppTransUtil.log("Res "+strJson);
			JSONObject jo = new JSONObject(strJson);
			return jo;

		}catch (Exception e) {
			LibAndTransUtil.log("Translation request error.", e);
			JSONObject jo = new JSONObject();
			try{
				jo.put(JsonParamData, null);
				jo.put(JsonParamStatus, 0);
				jo.put(JsonParamDetails, e.getMessage());
				return jo;
			}catch (Exception ex) {
				LibAndTransUtil.log("Json error.", ex);
				return null;
			}
		}
	}

	/*
	 * status 200 is OK. Other errors.
	 */
	public abstract void onExecute(String translation, int status, String details);

	@Override
	protected void onPostExecute(JSONObject result) {
		if(result==null){
			onExecute(null, 0, null);
			return;
		}

		/* Response JSON Example
		 * {
		 *  "responseData": {
		 *    "translatedText": "Hola, mi amigo!"
		 *  },
		 *   "responseDetails": null,
		 *  "responseStatus": 200
		 * }
		 */
		try{
			String trans = null;
			JSONObject o = null;
			try{
				o = result.getJSONObject(JsonParamData);
			}catch (Exception e) {}
			if(o!=null){
				trans = o.getString(JsonParamTranslated);
			}
			int status = result.getInt(JsonParamStatus);
			String details = result.getString(JsonParamDetails);
			onExecute(trans, status, details);

		}catch (Exception e) {
			LibAndTransUtil.log("Json error", e);
			onExecute(null, 0, e.getMessage());
			return;
		}
	}

	private HttpResponse transRequest(String str, String toLang) throws IOException{
		StringBuilder buf = new StringBuilder(GoogleLanguageURL);
		buf.append("?v=1.0");
		try{
			buf.append("&q="+URLEncoder.encode(str, "UTF-8"));
		}catch (Exception e) {}
		buf.append("&langpair=%7C"+toLang); // the source language is auto-detect
		LibAndTransUtil.log("Req "+buf.toString());
		HttpGet req = new HttpGet(buf.toString());
		return httpExecute(req);
	}

	private HttpResponse httpExecute(HttpRequestBase base) throws IOException{
		try{
			return this.client.execute(base);
		}catch (IOException e) {
			base.abort();
			throw e;
		}
	}

}
